package com.sage.ierp.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.sage.commons.AssertUtils;
import com.sage.dao.IndustryDao;
import com.sage.dao.model.Company;
import com.sage.dao.model.Industry;
import com.sage.dao.model.ServerISP;
import com.single.commons.StringUtils;
import com.single.exceptions.AssertException;


/**
 * ISP跳转
 * @author Administrator
 *
 */
public class ISPRedirectController {

	//@Autowired
	//private CompanyDao companyDao;
	@Autowired
	private IndustryDao industryDao;
	
	
	@RequestMapping("/redirect/{pIndustryPnkey}/{pCompanyPnkey}/{pISPName}")
	public ModelAndView redirect(@PathVariable("pIndustryPnkey") String pIndustryPnkey, @PathVariable("pCompanyPnkey") String pCompanyPnkey, 
			@PathVariable("pISPName") String pISPName) throws IOException, ServletException {
		ModelAndView modelView = new ModelAndView();
		try{
			AssertUtils.assertText(pIndustryPnkey, "10261", "请提供行业编号!");
			AssertUtils.assertText(pCompanyPnkey, "10262", "请提供企业编号!");
			AssertUtils.assertText(pISPName, "1023","请提供ISP(Internet Service Provider: 互联网服务提供商)编号!");
			
			Industry industry = industryDao.findByKey(pIndustryPnkey);
			AssertUtils.assertNull(industry, "10267", "目前没有存在编号为\"?\"的行业,请提供正确的行业编号!", '?', pIndustryPnkey);
			Company company = industry.getCompany(pCompanyPnkey);
			AssertUtils.assertNull(company, "10268","目前没有存在编号为\"?\"的企业,请提供正确的企业编号!", '?', pCompanyPnkey);
			ServerISP serverISP = company.getServer().getServerIspByKey(pISPName);
			AssertUtils.assertNull(serverISP, "10269", "目前没有存在编号为\"?\"的互联网服务提供商信息,请提供正确的互联网服务提供商编号!", '?', pISPName);
			
			Map<String, String> map = new HashMap<String, String>();
			map.put("addr", StringUtils.defaultIfEmpty(serverISP.getDomainName(), serverISP.getIp()));
			Integer port = serverISP.getPort();
			map.put("port", (port==null ? "" : ":" + port));
			map.put("erp_name", company.getErpName());
			map.put("isp", pISPName);
			String url = StringUtils.replace("http://{addr}{port}/{erp_name}?{isp}", map);
			modelView.setViewName("redirect:"+url);
		}catch (AssertException e) {
			modelView.addObject("exception", e);
			modelView.setViewName("../template/ierp_prompt.ftl");
			//redirect("../template/ierp_prompt.ftl");
		}
		
		return modelView;
	}
	
}
